package com.example.administrator.exkotlin.jetpack.room

import android.content.Context
import android.util.Log
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.administrator.exkotlin.jetpack.room.dao.BookDao
import com.example.administrator.exkotlin.jetpack.room.dao.UserDao
import com.example.administrator.exkotlin.jetpack.room.entity.Book
import com.example.administrator.exkotlin.jetpack.room.entity.User

/**
 * Author by lp,on 2020/11/19/019,11:53.
 *
 * Room关系型数据库分为三个组成部分
 * entity 实体类 定义表字段
 * dao 数据访问对象 增删改查
 * database 数据库信息管理 版本、包含哪些表、模式、升级等
 *
 */

@Database(version = 3, entities = [User::class,Book::class])
abstract class MyDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
    abstract fun bookDao(): BookDao

    //单例数据库操作对象
    companion object {
       private  val TAG="MyDatabase"
        private var instance: MyDatabase? = null

        //数据库升级 1到2
        val MIGRANTION_1_2 = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                //具体升级用到的sql语句
                //增加了一张表，表中具体的字段等
                database.execSQL("create table Book(id integer primary key autoincrement not null,bookName text not null,bookPrice integer not null)")
                Log.i(TAG,"数据库1-2更新成功")
            }

        }
        //数据库升级 2到3
        val MIGRANTION_2_3 = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                //具体升级用到的sql语句
                //增加了一张表，表中具体的字段等
                database.execSQL("alter table Book add author text not null default 'unknown'")
                Log.i(TAG,"数据库2-3更新成功")
            }

        }


        @Synchronized
        fun getDatabase(context: Context): MyDatabase {
            instance?.let {
                return it
            }
            return Room.databaseBuilder(context.applicationContext, MyDatabase::class.java, "my_room_data")
                    .allowMainThreadQueries()
                    .addMigrations(MIGRANTION_1_2,MIGRANTION_2_3)
                    .build()
                    .apply { instance = this }
        }
    }

}